package ltd.dujiabao.inventoryservice.service;

import io.seata.core.context.RootContext;
import lombok.extern.slf4j.Slf4j;
import ltd.dujiabao.common.dto.DeductStockDto;
import ltd.dujiabao.inventoryservice.dao.InventoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Bowie Du
 * @date 2025/7/22 20:09
 */
@Slf4j
@Service
public class InventoryService {
    @Autowired
    private InventoryRepository inventoryRepository;

    @Transactional(rollbackFor = Exception.class)
    public void deductStock(DeductStockDto dto) {
        log.info("XID: {}", RootContext.getXID());
        int effected = inventoryRepository.deductStock(dto.getProductId(), dto.getQuantity());
        if (effected <= 0) {
            throw new RuntimeException("fail to deduct stock.");
        }
    }
}
